import { Request, Response } from 'express';
import { config } from '@root/config';
import JWT from 'jsonwebtoken';
import { joiValidation } from '@global/decorator/joi-validation.decorator';
import HTTP_STATUS from 'http-status-codes';
import { authService } from '@service/db/auth.service';
import { loginSchema } from '@auth/schemes/signin';
import { IAuthDocument } from '@auth/interfaces/auth.interface';
import { BadRequestError } from '@global/helpers/error-handler';
import { userService } from '@service/db/user.service';
import { IResetPasswordParams, IUserDocument } from '@user/interfaces/user.interface';
import { mailTransport } from '@service/emails/email.transport';
import { forgotPasswordTemplate } from '@service/emails/template/forgot-password/forgot-password-template';
import { emailQueue } from '@service/queues/email.queue';
import moment from 'moment';
import publicIP from 'ip';
import { resetPasswordTemplate } from '@service/emails/template/reset-password/reset-password-template';


export class SignIn {
  @joiValidation(loginSchema)
  public async read(req: Request, res: Response): Promise<void> {
    const { username, password } = req.body;
    const existingUser: IAuthDocument = await authService.getAuthUserByUsername(
      username
    );
    if (!existingUser) {
      throw new BadRequestError('Invalid credentials');
    }

    const passwordsMatch: boolean = await existingUser.comparePassword(
      password
    );
    if (!passwordsMatch) {
      throw new BadRequestError('Invalid credentials');
    }
    const user: IUserDocument = await userService.getUserByAuthId(
      `${existingUser._id}`
    );
    const userJwt: string = JWT.sign(
      {
        userId: user._id,
        uId: existingUser.uId,
        email: existingUser.email,
        username: existingUser.username,
        avatarColor: existingUser.avatarColor,
      },
      config.JWT_TOKEN!
    );
    // await mailTransport.sendEmail('jmqpotato@icloud.com','test','this is a development test email');
    // const templateParams:IResetPasswordParams = {
    //   username:existingUser.username!,
    //   email:existingUser.email!,
    //   ipaddress:publicIP.address(),
    //   date:moment().format('YYYY/MM/DD HH:mm')
    // };

    // const resetLink = `${config.CLIENT_URL}/reset-password?token=12374838282839494`;
    //   // const resetLink = 'https://fanyi.baidu.com/?aldtype=16047#zh/en/%E4%BD%A0%E5%B0%B1%E6%98%AF%E4%B8%AAjb';
    //   // const template:string = forgotPasswordTemplate.passwordResetTemplate(existingUser.username!,resetLink);
    //   const template:string = resetPasswordTemplate.passwordResetConfirmationTemplate(templateParams);
    //   emailQueue.addEmailJob('forgotPasswordEmail',{template,receiverEmail:'jmqpotato@icloud.com',subject:'Password reset comfirmation'});
    req.session = { jwt: userJwt };
    const userDocument: IUserDocument = {
      ...user,
      authId: existingUser!._id,
      username: existingUser!.username,
      email: existingUser!.email,
      avatarColor: existingUser!.avatarColor,
      uId: existingUser!.uId,
      createdAt: existingUser!.createdAt,
    } as IUserDocument;
    res
      .status(HTTP_STATUS.OK)
      .json({
        message: 'User login successfully',
        user: userDocument,
        token: userJwt,
      });
  }
}
